// $Id: DqlExecuteHandler.java 13 2011-09-12 19:36:35Z huijzer@gmail.com $
package lime.dql.handler;

import java.util.Date;
import java.util.List;

import lime.common.DQLTemplate;
import lime.common.LimeException;
import lime.model.History;
import lime.service.RepositoryService;
import lime.service.SpringApplicationContext;
import lime.dql.view.DqlEditorView;
import lime.dql.view.DqlHistoryView;
import lime.dql.view.DqlResultsView;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;

import com.documentum.fc.client.IDfTypedObject;
import com.documentum.fc.common.DfException;

public class DqlExecuteHandler extends AbstractHandler {

	private RepositoryService repositoryService;
	private DQLTemplate dqlTemplate;

	public DqlExecuteHandler() {
		super();
		repositoryService = (RepositoryService) SpringApplicationContext.getBean("repositoryService");
		dqlTemplate = new DQLTemplate(repositoryService.getSession());
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		DqlEditorView editorView = (DqlEditorView) HandlerUtil.getActiveWorkbenchWindow(event).getActivePage()
				.findView(DqlEditorView.ID);
		String dql = editorView.getDql();

		try {
			List<IDfTypedObject> objectList = dqlTemplate.queryForObjects(dql);

			DqlResultsView view = (DqlResultsView) HandlerUtil.getActiveWorkbenchWindow(event).getActivePage()
					.findView(DqlResultsView.ID);
			view.update(objectList);

			DqlHistoryView historyView = (DqlHistoryView) HandlerUtil.getActiveWorkbenchWindow(event).getActivePage()
					.findView(DqlHistoryView.ID);
			History history = new History(dql, new Date());
			historyView.update(history);

		} catch (DfException e) {
			throw new LimeException(e);
		}

		return null;
	}

}
